// @Desc:
// @CreateTime: 2020/10/26
package statistics

import (
	"fmt"
	"net/http"

	"gitee.com/xuesongtao/gotool/xlog"
	"github.com/gin-gonic/gin"
	"mycrm.com/controller"
	. "mycrm.com/module"
	"mycrm.com/module/customer"
	"mycrm.com/module/statistics"
	"mycrm.com/module/user"
	"mycrm.com/utils"
)

func Index(c *gin.Context) {
	uid := c.Param("uid")
	roleId := c.Param("roleId")
	mostCustomerMap := make(map[string]interface{})
	today0, today23 := utils.GetCurDay0And23()
	callMostCustomerMap := make(map[string]interface{})
	isOkCallMostCustomerMap := make(map[string]interface{})
	todayData := make([]map[string]interface{}, 0)
	last30Data := make([]map[string]interface{}, 0)

	// 判断下是否为组长, 组长只能查看该小组的成员
	if roleId == "4" {
		var (
			groupId      int
			groupUserIds []int
		)
		// 查询该组长所在组 id
		Db.Model(&user.CrmUser{}).Where("id = ?", uid).Select("group_id").Scan(&groupId)
		// 获取所有组员
		Db.Model(&user.CrmUser{}).Where("group_id = ?", groupId).Select("id").Scan(&groupUserIds)
		Db.Model(&statistics.CrmStatistics{}).Where("user_id IN (?)", groupUserIds).Order("customer_total DESC").Limit(1).Select("name, customer_total").Scan(&mostCustomerMap)
		Db.Model(&statistics.CrmStatistics{}).Where("created_at BETWEEN ? AND ? AND user_id IN (?)", today0, today23, groupUserIds).Order("visits_day DESC").Limit(1).Select("name, visits_day").Scan(&callMostCustomerMap)
		Db.Model(&statistics.CrmStatistics{}).Where("created_at BETWEEN ? AND ? AND user_id IN (?)", today0, today23, groupUserIds).Order("isok_visits_day DESC").Limit(1).Select("name, isok_visits_day").Scan(&isOkCallMostCustomerMap)
		Db.Model(&statistics.CrmStatistics{}).Where("created_at BETWEEN ? AND ? AND user_id IN (?)", today0, today23, groupUserIds).Select("name, visits_day, isok_visits_day").Scan(&todayData)
		Db.Model(&statistics.CrmStatistics{}).Where("created_at BETWEEN ? AND ? AND user_id IN (?)", today0-30*24*3600, today23, groupUserIds).Select("name, isok_visits_day, created_at").Scan(&last30Data)
	} else {
		Db.Model(&statistics.CrmStatistics{}).Order("customer_total DESC").Limit(1).Select("name, customer_total").Scan(&mostCustomerMap)
		Db.Model(&statistics.CrmStatistics{}).Where("created_at BETWEEN ? AND ?", today0, today23).Order("visits_day DESC").Limit(1).Select("name, visits_day").Scan(&callMostCustomerMap)
		Db.Model(&statistics.CrmStatistics{}).Where("created_at BETWEEN ? AND ?", today0, today23).Order("isok_visits_day DESC").Limit(1).Select("name, isok_visits_day").Scan(&isOkCallMostCustomerMap)
		Db.Model(&statistics.CrmStatistics{}).Where("created_at BETWEEN ? AND ?", today0, today23).Select("name, visits_day, isok_visits_day").Scan(&todayData)
		Db.Model(&statistics.CrmStatistics{}).Where("created_at BETWEEN ? AND ?", today0-30*24*3600, today23).Select("name, isok_visits_day, created_at").Scan(&last30Data)
	}

	data := map[string]interface{}{
		"mostCustomerName":         mostCustomerMap["name"],
		"mostCustomerNum":          mostCustomerMap["customer_total"],
		"callMostCustomerName":     callMostCustomerMap["name"],
		"callMostCustomerNum":      callMostCustomerMap["visits_day"],
		"isOkCallMostCustomerName": isOkCallMostCustomerMap["name"],
		"isOkCallMostCustomerNum":  isOkCallMostCustomerMap["isok_visits_day"],
		"todayData":                todayData,
		"last30Data":               last30Data,
	}
	resp := controller.Response{
		Status:      1,
		Data:        data,
		Total:       0,
		CurrentPage: 0,
		TotalPage:   0,
	}
	c.JSON(http.StatusOK, resp)
}

// 关注微信后手机号是否与我们系统配对
func isAttention(openid string) string {
	var isAttention int
	Db.Table("crm_user").Select("is_attention").Where("open_id = ?", openid).Scan(&isAttention)
	xlog.Info("isAttention: ", isAttention)
	if isAttention == 0 {
		return "您的手机号码还没有进行配对, 请正确回复您的手机号码, 进行配对!"
	}
	return ""
}

// 微信中我的任务, 返回今日和已过期的回访
func MyTask2Wx(openid string) string {
	var customerInfos []customer.Customer
	_, today23 := utils.GetCurDay0And23()
	xlog.Info("time: ", today23)
	Db.Table("crm_user AS u").Joins("LEFT JOIN crm_customer AS c ON u.id = c.user_id").
		Where("u.open_id = ? and c.next_visit_at <= ?", openid, today23).Select("c.name, c.phone").Scan(&customerInfos)
	if len(customerInfos) == 0 { // 如果等于 0 时先判断下该用户是否手机配对
		res := isAttention(openid)
		if res != "" {
			return res
		}
	}

	// 按每行 14 个字符处理
	var (
		taskStr           string
		customer2PhoneStr string
		header            = "姓名          |      联系电话\n" +
			"-----------------------------\n"
		foot = "-----------------------------\n"
	)
	for _, customerInfo := range customerInfos {
		customer2PhoneStr += fmt.Sprintf("%s     |      %s\n", customerInfo.Name, customerInfo.Phone)
	}
	foot += fmt.Sprintf("今日总回访: %d", len(customerInfos))
	taskStr += header
	taskStr += customer2PhoneStr
	taskStr += foot
	return taskStr
}

// 统计发送个微信
func Statistics2Wx(openid string) string {
	// 判断下是否与我们系统进行配对
	res := isAttention(openid)
	if res != "" {
		return res
	}
	var (
		userInfo = struct {
			Id      int
			RoleId  int
			GroupId int
		}{}
		userStatisticsOne statistics.CrmStatistics   // 一个人
		userStatistics    []statistics.CrmStatistics // 多人
		respStr           string
	)
	Db.Table("crm_user AS u").Joins("JOIN crm_user2role AS u2r ON u.id = u2r.user_id").Select("u2r.role_id, u.id, u.group_id").Where("open_id = ?", openid).Scan(&userInfo)
	today0, today23 := utils.GetCurDay0And23()
	if userInfo.RoleId == 5 { // 员工只能查看自己
		Db.Table("crm_statistics").Where("created_at BETWEEN ? AND ? AND user_id = ?", today0, today23, userInfo.Id).Select("customer_total, visits_day, no_visits_day").Scan(&userStatisticsOne)
		respStr = fmt.Sprintf("今日回访数:    %d \n", userStatisticsOne.VisitsDay)
		respStr += fmt.Sprintf("今日未回访数:    %d \n", userStatisticsOne.NoVisitsDay)
		respStr += fmt.Sprintf("客户总数:    %d \n", userStatisticsOne.CustomerTotal)
	} else if userInfo.RoleId == 4 { // 组长, 查看该分组的
		var groupUserIds []int
		Db.Model(&user.CrmUser{}).Where("group_id = ?", userInfo.GroupId).Select("id").Scan(&groupUserIds)
		Db.Table("crm_statistics").Where("created_at BETWEEN ? AND ? AND user_id IN (?)", today0, today23, groupUserIds).Select("name, customer_total, visits_day, no_visits_day").Scan(&userStatistics)
	} else {
		Db.Table("crm_statistics").Where("created_at BETWEEN ? AND ?", today0, today23).Select("name, customer_total, visits_day, no_visits_day").Scan(&userStatistics)
	}

	// 组装多条数据
	if len(userStatistics) > 0 {
		for _, v := range userStatistics {
			respStr += fmt.Sprintf("------------- %s -----------\n", v.Name)
			respStr += fmt.Sprintf("今日回访数:    %d \n", v.VisitsDay)
			respStr += fmt.Sprintf("今日未回访数:    %d \n", v.NoVisitsDay)
			respStr += fmt.Sprintf("今日有效回访数:    %d \n", v.IsokVisitsDay)
			respStr += fmt.Sprintf("客户总数:    %d \n", v.CustomerTotal)
		}
	}

	if respStr == "" {
		respStr = "暂无数据"
	}
	return respStr
}
